package cn.atguigu.comsumer;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

/**
 * @author JiDingXia
 * @date 2025-02-26 22:56:02
 */
public class CustomConsumerByHand {
	public static void main(String[] args) {
		// 1. 创建kafka消费者配置类
		Properties properties = new Properties();
		// 2. 添加配置参数
		// 添加连接
		properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092,hadoop103:9092,hadoop104:9092");
		// 配置序列化 必须
		properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		// 配置消费者组
		properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group03");
		// 关闭自动提交
		properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
		//auto.offset.reset
		properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
		// 3. 创建kafka消费者
		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
		// 4. 设置消费主题  形参是列表
		consumer.subscribe(Arrays.asList("first"));
		// 5. 消费数据
		while (true) {
			// 6. 读取消息
			ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(1));
			// 7. 输出消息
			for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
				System.out.println("消息:" + consumerRecord.value() + ", 主题:" + consumerRecord.topic() +
					", 分区:" + consumerRecord.partition() + ", 偏移量:" + consumerRecord.offset());
			}
			//异步提交offset
			consumer.commitAsync(new OffsetCommitCallback() {
				/**
				 * 回调函数输出,也可以不写
				 * @param offsets   offset信息
				 * @param exception 异常
				 */
				@Override
				public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
					// 如果出现异常打印
					if (exception != null) {
						System.err.println("Commit failed for " + offsets);
					}
				}
			});
		}
	}
}
